import { ElMessage } from "element-plus";
export const downloadKml = (routeForm) => {
  if (!routeForm.waypoints.length) {
    ElMessage.warning("暂无航点可导出");
    return;
  }
  const kmlPoints = routeForm.waypoints
    .map((wp, index) => {
      const name = (wp.name || `航点${index + 1}`).trim();
      const lon = Number(wp.lng).toFixed(6);
      const lat = Number(wp.lat).toFixed(6);
      const alt = Number(wp.altitude || routeForm.defaultAltitude || 0).toFixed(
        2
      );
      return `      <Placemark>
        <name>${name}</name>
        <description><![CDATA[高度: ${alt} m]]></description>
        <Point><coordinates>${lon},${lat},${alt}</coordinates></Point>
      </Placemark>`;
    })
    .join(" ");
  const pathCoords = routeForm.waypoints
    .map(
      (wp) =>
        `${Number(wp.lng).toFixed(6)},${Number(wp.lat).toFixed(6)},${Number(
          wp.altitude || routeForm.defaultAltitude || 0
        ).toFixed(2)}`
    )
    .join(" ");
  const kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>${routeForm.name || "航线"}</name>
    <description><![CDATA[${routeForm.description || ""}]]></description>
    <Style id="routeStyle">
      <LineStyle><color>ff457aff</color><width>3</width></LineStyle>
      <PolyStyle><color>40ff7a45</color></PolyStyle>
    </Style>
    <Placemark>
      <name>${routeForm.name || "航线"}</name>
      <styleUrl>#routeStyle</styleUrl>
      <LineString>
        <coordinates>${pathCoords}</coordinates>
      </LineString>
    </Placemark>
${kmlPoints}
  </Document>
</kml>`;
  const blob = new Blob([kml], {
    type: "application/vnd.google-earth.kml+xml",
  });
  const url = URL.createObjectURL(blob);
  const filename = `${(routeForm.name || "route").trim() || "route"}.kml`;
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};
